package com.xingfudazi.web.controller.app;

import com.xingfudazi.app.domain.AppAccount;
import com.xingfudazi.app.domain.AppMember;
import com.xingfudazi.app.enums.MemberTypeEnum;
import com.xingfudazi.app.service.AuthService;
import com.xingfudazi.app.service.IAppAccountService;
import com.xingfudazi.app.service.IAppMemberService;
import com.xingfudazi.common.core.domain.Result;
import com.xingfudazi.common.core.domain.entity.SysUser;
import com.xingfudazi.common.core.domain.model.LoginUser;
import com.xingfudazi.common.exception.ExceptionEnum;
import com.xingfudazi.common.exception.ServiceException;
import com.xingfudazi.common.utils.SecurityUtils;
import com.xingfudazi.framework.web.service.TokenService;
import com.xingfudazi.framework.web.service.UserDetailsServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

/**
 * 小程序auth
 *
 * @author YuJiaMing
 * date 2023年11月03日 08:47
 */
@Api(tags = {"小程序认证"})
@RestController
@RequestMapping("wechat/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private IAppMemberService appMemberService;

    @Autowired
    private IAppAccountService accountService;

    /**
     * 注册接口、即小程序选择手机号后调用
     * 正常：返回被调用的手机号码
     * 异常：手机号未在系统中录入，抛出异常 {@link ExceptionEnum#ACCOUNT_UNAUTHORIZED}
     */
    @ApiOperation(value = "注册", notes = "根据获取到的手机号code完成注册")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "code", value = "微信小程序code", required = true, dataTypeClass = String.class)
    )
    @GetMapping("register")
    public Result<String> register(@RequestParam String code) {
        AppAccount appAccount = authService.register(code);
        return Result.success(appAccount.getPhone());
    }

    @GetMapping("tempRegister")
    public Result<String> tempRegister(@RequestParam String member) {
        AppAccount appAccount = authService.tempRegister(member);
        return Result.success(appAccount.getPhone());
    }

    /**
     * 微信登录、根据code和手机号返回
     * 通过微信code获取微信 open_id 和session_key、并存储到库中
     * 需要注意非首次登录需要校验 已经绑定openId的手机号和传递的是否一致
     *
     * @param code  微信登录code
     * @param phone 当前登录的手机号
     */
    @ApiOperation(value = "登录", notes = "微信小程序登录")
    @PostMapping("login")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "code", value = "微信小程序code", required = true, dataTypeClass = String.class),
            @ApiImplicitParam(name = "phone", value = "微信小程序电话", required = true, dataTypeClass = String.class)
    })
    public Result<String> login(@RequestParam String code, @RequestParam String phone) {

        // 登录
        AppMember appNumber = authService.login(code, phone);

        // 构造登录对象
        LoginUser loginUser = new LoginUser();
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setUserId(appNumber.getId());
        loginUser.setUserName(phone);
        loginUser.setNickName(appNumber.getNickName());
        loginUser.setUser(new SysUser());
        String token = tokenService.createTokenWx(loginUser);
        return Result.success(token);
    }


    @Transactional(rollbackFor = Exception.class)
    @GetMapping("change")
    public Result<String> change(@RequestParam MemberTypeEnum type) {
        Long userId = SecurityUtils.getUserId();
        AppMember appMember = this.appMemberService.selectAppMemberById(userId);
        if (appMember.getType().equals(type.name())) {
            throw new ServiceException("无需重复切换");
        }



        // 获取最新的 app_member
        Long aid = appMember.getAid();
        appMember = this.appMemberService.selectAppMember(aid, type);
        if (appMember == null) {
            throw new ServiceException("请先进行申请");
        }

        // 获取token
        LoginUser loginUser = new LoginUser();
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setUserId(appMember.getId());
        loginUser.setUserName(appMember.getPhone());
        loginUser.setNickName(appMember.getNickName());
        loginUser.setUser(new SysUser());
        String token = tokenService.createTokenWx(loginUser);

        // 更新account
        AppAccount appAccount = new AppAccount();
        appAccount.setId(aid);
        appAccount.setMemberType(type.name());
        this.accountService.updateAppAccount(appAccount);
        return Result.success(token);
    }

}
